//
//  NewFeatureViewController.swift
//  sinaDemo
//
//  Created by mac on 15/12/16.
//  Copyright © 2015年 zhouxubin. All rights reserved.
//

import UIKit
import SnapKit

private let reuseIdentifier = "Cell"
private let featureCellCount = 4

class NewFeatureViewController: UICollectionViewController {
    
    // 设置布局
    init() {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSizeMake(screenBounds.width, screenBounds.height)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = .Horizontal
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // 设置滚动方向和分页效果
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.bounces = false
        
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.registerClass(FeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    // MARK: UICollectionViewDataSource

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return featureCellCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! FeatureCell
        
        cell.index = indexPath.item
        // Configure the cell
    
        return cell
    }
    
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        // 获取正在显示的cell
        let displayCell = collectionView.visibleCells().last as! FeatureCell
        // 获取正确的indexpath
        let index = collectionView.indexPathForCell(displayCell)!
        
        // 当滚到第四个的时候开始动画
        if index.item == featureCellCount - 1 {
            displayCell.startAnimation()
        }
    }

}

class FeatureCell: UICollectionViewCell {
    
    // 图片的下标,重写setter方法
    var index = 0 {
        didSet {
            largeImage.image = UIImage(named: "new_feature_" + "\(index + 1)")
        }
    }
    
    // MARK: 懒加载
    // 大图
    private lazy var largeImage: UIImageView = UIImageView(image: UIImage(named: "new_feature_1"))
    
    // 开始按钮
    private lazy var startButton: UIButton = {
        let button = UIButton()
        button.hidden = true
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        button.setTitle("开始微博", forState: UIControlState.Normal)
        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        // 添加按钮的点击事件
        button.addTarget(self, action: "clickStartButton", forControlEvents: UIControlEvents.TouchUpInside)
        return button
        }()
    
    // 开始按钮的点击事件
    @objc private func clickStartButton() {
        // 切换根控制器
        notificationCenter.postNotificationName(switchRootVCNotification, object: nil)
    }
    
    // MARK: 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        // 添加控件
        contentView.addSubview(largeImage)
        contentView.addSubview(startButton)
    }
    
    // MARK:设置frame
    override func layoutSubviews() {
        super.layoutSubviews()
        // 设置大图的约束
        largeImage.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        // 设置按钮的约束
        startButton.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(contentView.snp_centerX)
            make.centerY.equalTo(contentView.snp_centerY).offset(200)
        }
    }
    
    // 按钮的动画
    private func startAnimation() {
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        startButton.hidden = false
        // 第三个参数是弹簧系数  第四个参数是加速度
        UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: [], animations: { () -> Void in
            self.startButton.transform = CGAffineTransformIdentity
            }) { (_) -> Void in
                print("OK")
        }
    }
    
    // MARK: 如果从xib和sb中加载就会报错
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
